import React, {useEffect, useState} from "react"
import "../../../../assets/scss/pages/release-form.scss"
import {
  Button, Card,
  CardBody,
  CardFooter, CardHeader, CardTitle, Row, UncontrolledCollapse, UncontrolledTooltip, Col
} from "reactstrap";
import {Question} from "./icons";
import Track from "./Track";
import {RELEASE_FORM_ADD_TRACK} from "../../../../redux/constants/releaseDetail/tabInfo";


const TrackList = props => {
  const {data, activeStage, isEdited, releaseId, code} = props;
  const {setFieldData, setActiveStage, setFieldIdData, setNotification, updateReleaseByCode, updateReleaseById} = props;
  const [mQuery, setMQuery] = useState({matches: window.innerWidth < 1024});

  const AddTrack = () => {
    setFieldData(RELEASE_FORM_ADD_TRACK, null, null)
  }

  useEffect(() => {
    let mediaQuery = window.matchMedia("(max-width: 1024px)");
    mediaQuery.addListener(setMQuery);
    return () => mediaQuery.removeListener(setMQuery);
  }, []);

  useEffect(() => {
    const updateWindowDimensions = () => {
      if (isEdited && releaseId) {
        const wrapper = document.querySelector('.wrapper')
        if (!wrapper.classList.contains('menu-collapsed')) {
          setMQuery({matches: window.innerWidth < 1640})
        }
      }

    };

    window.addEventListener("resize", updateWindowDimensions);

    return () => window.removeEventListener("resize", updateWindowDimensions)

  }, []);

  const goPrev = () => {
    setActiveStage(activeStage - 1 >= 0 ? activeStage - 1 : 0)
  }

  const Save = () => {
    let trackValidId = null;
    if (data.tracks === null || data.tracks.length === 0) {
      setNotification('Добавьте хотя бы одну композицию!', 'error')
      return;
    }

    const nameValid = data.tracks.some((track, trackId) => {
      trackValidId = trackId;
      return track.name.trim() === ''
    })
    if (nameValid) {
      setNotification(`Введите название ${trackValidId + 1} композиции!`, 'error')
      return;
    }

    const trackValid = data.tracks.some((track, trackId) => {
      trackValidId = trackId;
      const endElement = track.track_composer[track.track_composer.length - 1]
      return track.track_composer.length === 0 || endElement === null || endElement.trim() === ''
    })
    if (trackValid) {
      setNotification(`У композиции ${trackValidId + 1} не введен автор музыки!`, 'error')
      return;
    }

    const textValid = data.tracks.some((track, trackId) => {
      trackValidId = trackId;
      const endElement = track.text_composer[track.text_composer.length - 1]
      return track.text_composer.length === 0 || endElement === null || endElement.trim() === ''
    })
    if (textValid) {
      setNotification(`У композиции ${trackValidId + 1} не введен автор текста!`, 'error')
      return;
    }

    data.type_id = data.type.id
    data.genre_id = data.genre.id
    data.subgenre_id = data.subgenre.id
    data.cover_id = data.cover.id

    if (isEdited && releaseId) {
      updateReleaseById(releaseId, data)
    } else {
      updateReleaseByCode(code, data).then(() => {
        setActiveStage(activeStage + 1)
      })
    }
  }


  const Titles = () => {
    return (
      <Row>
        <Col className="d-flex justify-content-center">
          <div className="my-auto">
            <span className="name">Композиция</span>
            <span id="name-tooltip">
                  <Question/>
                  <UncontrolledTooltip
                    placement="top"
                    target="name-tooltip"
                  >
                    Hello World!
                  </UncontrolledTooltip>
                </span>
            <span className="required">*</span>
          </div>
        </Col>
        <Col className="d-flex justify-content-center">
          <div className="my-auto">
            <span className="name">Автор музыки</span>
            <span id="track-composer-tooltip">
                  <Question/>
                  <UncontrolledTooltip
                    placement="top"
                    target="track-composer-tooltip"
                  >
                    Hello World!
                  </UncontrolledTooltip>
                </span>
            <span className="required">*</span>
          </div>
        </Col>
        <Col className="d-flex justify-content-center">
          <div className="my-auto">
            <span className="name">Автор текста</span>
            <span id="text-composer-tooltip">
                  <Question/>
                  <UncontrolledTooltip
                    placement="top"
                    target="text-composer-tooltip"
                  >
                    Hello World!
                  </UncontrolledTooltip>
                </span>
            <span className="required">*</span>
          </div>
        </Col>
        <Col className="d-flex justify-content-center">
          <div className="my-auto">
            <span className="name">Совместно с</span>
            <span id="together-with-tooltip">
                  <Question/>
                  <UncontrolledTooltip
                    placement="top"
                    target="together-with-tooltip"
                  >
                    Hello World!
                  </UncontrolledTooltip>
                </span>
          </div>
        </Col>
      </Row>
    )
  }


  return (
    <div className="TrackList">
      <CardBody className="pb-0 pt-2 card-bdy">
        {
          mQuery && !mQuery.matches ?
            <div>
              <Titles/>
              {
                data.tracks && data.tracks.map((value, id) => {
                  return (
                    <div className={`${id === 0 ? '' : 'mt-3'}`} key={id}>
                      <Track setFieldIdData={setFieldIdData} value={value} id={id}/>
                    </div>
                  )
                })
              }
            </div> :
            <div className="vx-collapse collapse-bordered collapse-icon accordion-icon-rotate">
              {
                data.tracks && data.tracks.map((value, id) => {
                  return (
                    <Card className="border-0 mb-1">
                      <CardHeader className={'collapse-card-header'} id={`collapse-${id}`}>
                        <CardTitle className="lead collapse-title collapsed">
                          {value.name || 'Без названия'}
                        </CardTitle>
                      </CardHeader>
                      <UncontrolledCollapse toggler={`#collapse-${id}`}>
                        <CardBody className={'collapse-card-body'}>
                          <div className={'collapse-tracks'}>
                            <Titles/>
                            <div className={`${id === 0 ? '' : 'mt-3'}`} key={id}>
                              <Track collapse={true} setFieldIdData={setFieldIdData} value={value} id={id}/>
                            </div>
                          </div>
                        </CardBody>
                      </UncontrolledCollapse>
                    </Card>
                  )
                })
              }
            </div>

        }
        <div className="d-flex justify-content-center align-content-end mt-3">
          <Button.Ripple className="cursor-pointer" onClick={AddTrack} color="danger">Добавить</Button.Ripple>
        </div>
      </CardBody>
      <CardFooter className="border-0 pt-0 d-flex justify-content-between flex-wrap w-100 mt-3">
        <Button.Ripple className="cursor-pointer mt-1" onClick={goPrev} outline color="primary">Предыдущий
          шаг</Button.Ripple>
        <Button.Ripple className="cursor-pointer mt-1" onClick={Save} color="primary">Сохранить</Button.Ripple>
      </CardFooter>
    </div>
  )
}

export default TrackList

